import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Menu, Dropdown,Button,Card,Row, Col,Icon, Form, Input,message
} from 'antd';
import styles from './style.less';
import docCookies from "../../common/DocCookies";

const FormItem = Form.Item;
@connect(state => ({
  autoMenu: state.autoMenu,
}))
@Form.create()
export default class RdAutoMenu extends PureComponent {

  state = {
    rsId:docCookies.getItem("rsId"),

    mainMenuValues:[],
    menuCIndex:0,
    addSpanSize:21,

    subMenuValues:[[],[]],
    subMenuMaxCount:5,
    subMenuCIndex:0,
    subMenuIsMax:[false,false,false,false,false],


    formLoading:false,
    showSubMenu:false,
  };

  componentDidMount() {
    this.loadMethod();
  }

  //加载默认值
  loadMethod(){
    const { dispatch } = this.props;
    const params = {
      rsId: this.state.rsId,
    };
    dispatch({
      type: 'autoMenu/fetchGetAutoMenuDetail',  //请求的action
      payload:params,
      callback:(res) =>{
        var isMax = this.state.subMenuIsMax;
        for(var i in res.subButton){
          var len = res.subButton[i].length;
          if(len >= this.state.subMenuMaxCount){
            isMax[i] = true;
          }
        }
        this.setState({
          mainMenuValues: res.menuButton,
          subMenuValues: res.subButton,
          subMenuIsMax:isMax
        });


        this.changeAddSpanSize();
      }
    });
  }

  //主菜单添加
  addMenuClick = (cIndex) =>{
    const { mainMenuValues } = this.state;
    const { form } = this.props;
    let menuLen = mainMenuValues.length;
    if(menuLen < 3){
      form.resetFields();
      let _value = {
        menuName:'默认菜单',
        menuUrl:'',
        subMenuVisible:true
      };
      for(var i=0;i<menuLen;i++){
        mainMenuValues[i].subMenuVisible = false;
      }
      mainMenuValues[menuLen] = _value;

      this.setState({
        menuCIndex:menuLen
      })

      form.setFieldsValue({
        menuName:mainMenuValues[cIndex].menuName,
        menuUrl:mainMenuValues[cIndex].menuUrl
      });

      this.changeAddSpanSize();
    }
  }

  //删除主菜单
  delMainMenu = () =>{
    const { mainMenuValues,menuCIndex,subMenuValues } = this.state;
    mainMenuValues.splice(menuCIndex,1);
    subMenuValues.splice(menuCIndex,1);
    this.setState({
      mainMenuValues:mainMenuValues.concat([]),
      subMenuValues:subMenuValues.concat([]),
    })
    this.changeAddSpanSize();

    const { form } = this.props;
    form.setFieldsValue({
      menuName:"默认菜单",
      menuUrl:""
    });

  }

  //动态调整添加主菜单按钮
  changeAddSpanSize(){
    const { mainMenuValues } = this.state;
    var addSpanSize = 0;
    let menuLen = mainMenuValues.length;
    if(menuLen == 0) addSpanSize = 21;
    if(menuLen == 1) addSpanSize = 10;
    if(menuLen == 2) addSpanSize = 7;
    if(menuLen == 3) addSpanSize = 0;
    this.setState({
      addSpanSize:addSpanSize
    })
  }

  //主菜单点击事件
  menuClick = (index) =>{
    const { mainMenuValues  } = this.state;
    const { form } = this.props;

    this.setState({
      showSubMenu:false
    })

    //此处 切换菜单时，关闭当前currentIndex的menu，然后重新设置值
    let menuLen = mainMenuValues.length;
    for(var i=0;i<menuLen;i++){
      mainMenuValues[i].subMenuVisible = false;
    }
    mainMenuValues[index].subMenuVisible = true;
    form.setFieldsValue({
      menuName:mainMenuValues[index].menuName,
      menuUrl:mainMenuValues[index].menuUrl
    });
    this.setState({
      mainMenuValues:mainMenuValues,
      menuCIndex:index
    })
  }

  mainMenuNameAlidator = (rule, value, callback) =>{
    const { mainMenuValues } = this.state;
    if(value==""){
      message.error("菜单名称不能为空！");
    }else{
      if(this.len(value)>8){
        message.error("菜单名称不超过4个汉字或8个字母！");
      }
    }
    let tmpMainMenuValues = mainMenuValues;
    tmpMainMenuValues[this.state.menuCIndex].menuName = value;
    this.setState({
      mainMenuValues: tmpMainMenuValues
    });
    callback();
  }
  mainMenuUrlValidator = (rule, value, callback) =>{
    if(value == "") {
      message.error("链接地址不能为空！");
    }
    const { mainMenuValues } = this.state;
    let tmpMainMenuValues = mainMenuValues;
    tmpMainMenuValues[this.state.menuCIndex].menuUrl = value;
    this.setState({
      mainMenuValues: tmpMainMenuValues
    });
    callback();
  }

  len(s) {
    var l = 0;
    var a = s.split("");
    for (var i = 0; i < a.length; i++) {
      if (a[i].charCodeAt(0) < 299) {
        l++;
      } else {
        l += 2;
      }
    }
    return l;
  }

  //子菜单点击
  subMenuClick = (pIndex,index) =>{
    const { form } = this.props;
    const { subMenuValues } = this.state;
    this.setState({
      showSubMenu:true,
      subMenuCIndex:index
    })
    form.setFieldsValue({
      subMenuName:subMenuValues[pIndex][index].menuName,
      subMenuUrl:subMenuValues[pIndex][index].menuUrl
    });
  }

  //添加子菜单
  addSubMenuClick = (index) =>{
    const { subMenuValues ,subMenuMaxCount,subMenuIsMax} = this.state;
    let _c_value = {
      menuName:'子菜单名称',
      menuUrl:''
    };
    if(!subMenuValues[index]){
      subMenuValues[index]=[];
    }

    if(subMenuValues[index].length < subMenuMaxCount){
      subMenuValues[index].push(_c_value);
      this.setState({
        subMenuValues:subMenuValues.concat([]),
      })
      if(subMenuValues[index].length == subMenuMaxCount){
        subMenuIsMax[index]=true;
        this.setState({
          subMenuIsMax:subMenuIsMax
        })
      }
    }else{
      message.warning("每个菜单最多添加"+subMenuMaxCount+"个子菜单")
    }
  }

  //删除子菜单
  delSubMenuItem = () =>{
    const { subMenuCIndex ,menuCIndex ,subMenuValues,subMenuIsMax } = this.state;
    subMenuValues[menuCIndex].splice(subMenuCIndex,1);
    subMenuIsMax[menuCIndex]=false;
    this.setState({
      subMenuValues:subMenuValues.concat([]),
      subMenuIsMax:subMenuIsMax
    })

    const { form } = this.props;
    form.setFieldsValue({
      subMenuName:"子菜单名称",
      subMenuUrl:""
    });
  }

  subMenuNameValidator = (rule, value, callback) =>{
    var self = this;
    const { subMenuValues } = this.state;
    if(value==""){
      message.error("子菜单名称不能为空！");
    }else{
      if(this.len(value)>16){
        message.error("子菜单名称字数不超过8个汉字或16个字母！");
      }
    }
    let tmpSubMenuValues = subMenuValues;
    tmpSubMenuValues[this.state.menuCIndex][this.state.subMenuCIndex].menuName = value;
    this.setState({
      subMenuValues: tmpSubMenuValues
    });
    callback();
  }
  subMenuUrlValidator = (rule, value, callback) =>{
    const { subMenuValues } = this.state;
    let tmpSubMenuValues = subMenuValues;
    tmpSubMenuValues[this.state.menuCIndex][this.state.subMenuCIndex].menuUrl = value;
    this.setState({
      subMenuValues: tmpSubMenuValues
    });
    callback();
  }

  //保存和提交
  submitFrom = (mainMenuValues ,subMenuValues) =>{
    const { dispatch} = this.props;
    if(mainMenuValues.length == 0){
      message.error("至少包含一个主菜单");
      return ;
    }
    for(var i=0;i<mainMenuValues.length;i++){
      if(mainMenuValues[i].menuName == ""){
        message.error("主菜单名称不能为空");
        return ;
      } else if(this.len(mainMenuValues[i].menuName)>8){
          message.error("主菜单名称不超过4个汉字或8个字母！");
          return ;
      }
      if(mainMenuValues[i].menuUrl == ""){
        message.error("主菜单链接地址不能为空");
        return ;
      }
    }
    for(var i=0;i<subMenuValues.length;i++){
      for(var j=0;j<subMenuValues[i].length;j++) {
        if(subMenuValues[i][j].menuName == ""){
          message.error("子菜单名称不能为空");
          return ;
        } else if(this.len(subMenuValues[i][j].menuName)>16){
          message.error("子菜单名称不超过8个汉字或16个字母！");
          return ;
        }
        if(subMenuValues[i][j].menuUrl == ""){
          message.error("子菜单链接地址不能为空");
          return ;
        }
      }
    }
    let values = {
      rsId:this.state.rsId,
      menuButton:mainMenuValues,
      subButton:subMenuValues
    }
    dispatch({
      type: 'autoMenu/fetchSaveAutoMenu',  //请求的action
      payload:values,
      callback:(res) =>{
        message.success(res.msg);
      }
    });

  }

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { formLoading ,mainMenuValues,subMenuValues,addSpanSize,showSubMenu,subMenuIsMax} = this.state;
    var mainMenuValuesTmp = mainMenuValues ;
    var subMenuValuesTmp = subMenuValues;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const subMenu = (index) =>(
      <Menu>
        {subMenuItems(index)}
        <Menu.Item style={{display:subMenuIsMax[index]?'none':'block'}}>
          <Button type="dashed" style={{width:'100%'}}  onClick={()=>this.addSubMenuClick(index)} icon="plus">
            添加子菜单
          </Button>
        </Menu.Item>
      </Menu>
    );
    const subMenuItems = (pIndex) =>{
      if(subMenuValues[pIndex]){
        return subMenuValues[pIndex].map((item, index) => {
          var uniqueKey = pIndex+""+index;
          return (
            <Menu.Item key={uniqueKey}>
              <Button type="dashed" style={{width:'100%'}}  onClick={()=>this.subMenuClick(pIndex,index)} >
                {item.menuName}
              </Button>
            </Menu.Item>
          );
        })
      }
    };

    const menuItems = mainMenuValues.map((item, index) => {
      var _span = 21;
      if(mainMenuValues.length == 1) _span = 11;
      if(mainMenuValues.length != 1) _span = 7;
      return (
        <Col span={_span} key={index}>
          <Dropdown overlay={subMenu(index)} placement="topCenter" visible={item.subMenuVisible}>
            <Button type="dashed" style={{width:'100%',padding:'0 6px'}} onClick={()=>this.menuClick(index)}>
              {item.menuName}
            </Button>
          </Dropdown>
        </Col>
      );
    })

    const menuExtraBtn = (
      <Row gutter={0}>
        <Col span={11}>
          <Button type="primary" ghost style={{padding:'0 6px'}} onClick={()=>this.delMainMenu()} icon="minus">
              删除菜单
          </Button>
        </Col>
      </Row>
    )

    const subMenuExtraBtn = (
      <Row gutter={0}>
        <Col span={11}>
          <Button type="primary" ghost style={{padding:'0 6px'}} onClick={()=>this.delSubMenuItem()} icon="minus">
            删除子菜单
          </Button>
        </Col>
      </Row>
    )

    return (
      <Card title="自定义表单" >
        <Row gutter={16}>
          <Col className="gutter-row" span={4}>
          </Col>
          <Col className="gutter-row" span={5}>
            <Card className={styles.myMobileStyle}>
              <div style={{height:60,width:'100%',backgroundImage:"url("+require("../../../public/head.png")+")",backgroundSize:"100% 100%"}}>
                 <div style={{height:60,lineHeight:'80px',textAlign: 'center',fontSize: 20,color: 'white'}}>
                   949交通广播
                 </div>
              </div>
              <div style={{marginTop:450}}>

              </div>
              <Row gutter={0} style={{height:33,width:'100%',backgroundImage:"url("+require("../../../public/footer.png")+")",backgroundSize:"100% 100%"}}>
                <Col span={3} />
                {menuItems}
                <Col span={addSpanSize} style={{display:addSpanSize==0?'none':'block'}}>
                  <Button type="dashed" style={{width:'100%',padding:'0 6px'}} onClick={()=>this.addMenuClick(mainMenuValues.length)} icon="plus">
                    添加菜单
                  </Button>
                </Col>
              </Row>
            </Card>
          </Col>
          <Col className="gutter-row" span={1}>
          </Col>
          <Col className="gutter-row" span={10} style={{height:543}}>
            <Form
              hideRequiredMark
              style={{ marginTop: 8 }}
            >
            <Card title="菜单名称" style={{height:"100%",display:showSubMenu?'none':'block'}} extra={menuExtraBtn}>
                <FormItem
                  {...formItemLayout}
                  label="菜单名称"
                >
                  {getFieldDecorator('menuName',{
                    rules:[{
                      required: true,
                      message:"字数不超过4个汉字或8个字母",
                    },{
                      validator:this.mainMenuNameAlidator
                    }],
                    initialValue:"默认菜单"
                  })(
                    <Input placeholder="菜单名称" />
                  )}
                </FormItem>
              <FormItem
                {...formItemLayout}
                label="链接地址"
              >
                {getFieldDecorator('menuUrl',{
                  rules:[{
                    required: true,
                    message:"链接地址",
                  },{
                    validator:this.mainMenuUrlValidator
                  }]
                })(
                  <Input placeholder="链接地址"/>
                )}
              </FormItem>
            </Card>
            <Card title="子菜单名称" style={{height:"100%",display:showSubMenu?'block':'none'}} extra={subMenuExtraBtn}>
                <FormItem
                  {...formItemLayout}
                  label="子菜单名称"
                >
                  {getFieldDecorator('subMenuName',{
                    rules:[{
                      required: true,
                      message:"字数不超过8个汉字或16个字母",
                    },{
                      validator:this.subMenuNameValidator
                    }]
                  })(
                    <Input placeholder="子菜单名称" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="链接地址"
                >
                  {getFieldDecorator('subMenuUrl',{
                    rules:[{
                      required: true,
                      message:"链接地址",
                    },{
                      validator:this.subMenuUrlValidator
                    }]
                  })(
                    <Input placeholder="链接地址"/>
                  )}
                </FormItem>
            </Card>
            </Form>
          </Col>
          <Col className="gutter-row" span={4}>
          </Col>
        </Row>
        <Row gutter={16} style={{marginTop:25}}>
          <Col className="gutter-row" span={9}>
          </Col>
          <Col className="gutter-row" span={4}>
            <Button type="primary" loading={formLoading}  onClick={()=>this.submitFrom(mainMenuValuesTmp,subMenuValuesTmp)}>
            保存并发布
          </Button>
          </Col>
          <Col className="gutter-row" span={11}>
          </Col>
        </Row>
      </Card>
    );
  }
}
